use idgen::IDGen;

use crate::{
    dao::ageing::{self, Ageing},
    utils::{date_util, response::R},
};

#[tauri::command]
pub async fn save_ageing(date: String, work_time: f64, work_num: f64) -> R<String> {
    let mut info = Ageing::default();
    let idgen = IDGen::new(1);
    let id = idgen.new_id();
    info.id = id.to_string();
    info.date = date;
    info.work_time = work_time;
    info.work_num = work_num;
    if ageing::save(info).await {
        return R::success();
    }
    R::fail("保存失败！")
}

#[tauri::command]
pub async fn update_ageing(date: String, work_time: f64, work_num: f64) -> R<String> {
    let mut info = Ageing::default();
    info.date = date;
    info.work_time = work_time;
    info.work_num = work_num;
    if ageing::update_by_date(info).await {
        return R::success();
    }
    R::fail("保存失败！")
}

#[tauri::command]
pub async fn get_info_by_date(date: String) -> R<Ageing> {
    let data = ageing::get_info_by_date(date.clone()).await;
    match data {
        Some(data) => {
            return R::data(Some(data));
        }
        None => {
            let mut info = Ageing::default();
            let idgen = IDGen::new(1);
            let id = idgen.new_id();
            info.id = id.to_string();
            info.date = date;
            info.work_time = 0.0;
            info.work_num = 0.0;
            let _ = ageing::save(info).await;
        }
    }
    R::data(data)
}

#[tauri::command]
pub async fn get_list_by_date(date: String) -> R<Vec<Ageing>> {
    R::data(ageing::get_list_by_date(date).await)
}

#[tauri::command]
pub async fn get_list_by_dates(dates: Vec<String>) -> R<Vec<Ageing>> {
    R::data(ageing::get_list_by_dates(dates).await)
}

#[tauri::command]
pub async fn get_month_total_work_info(year: i32, month: u32) -> R<(f64, f64)> {
    let list = date_util::get_days_of_month(year, month);
    let datas = ageing::get_list_by_dates(list).await;
    match datas {
        Some(list) => {
            let mut total_time = 0.0;
            let mut total_num = 0.0;
            for i in list.iter() {
                total_time += i.work_time;
                total_num += i.work_num;
            }
            return R::data(Some((total_time, total_num)));
        }
        None => {
            return R::data(Some((0.0, 0.0)));
        }
    }
}
